package com.na.onlineservey.question


import com.docu.common.Action
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import com.na.onlineservey.QuestionService
import com.na.onlineservey.Question
import com.na.onlineservey.QuestionAnsweringOption

@Component("createQuestionAction")
class CreateQuestionAction extends Action {

    @Autowired
    QuestionService questionInstanceService

    public Object preCondition(Object params, Object object) {

        try {
            Map map = [:];
            Question questionInstance = new Question(params)
            if (!questionInstance.validate()) {
                return questionInstance
            }
            List<QuestionAnsweringOption> questionAnsweringOptionList = [];
            println params
            params?.item?.each {key, val ->
                if (val instanceof Map) {
                    QuestionAnsweringOption questionAnsweringOption = new QuestionAnsweringOption(val)
                    questionAnsweringOptionList.add(questionAnsweringOption)
                }
            }
            map.put("questionInstance", questionInstance)
            map.put("questionAnsweringOptionList", questionAnsweringOptionList)
            return map;
        } catch (Exception ex) {
            log.error(ex.message)
            return null
        }
    }

    public Object execute(Object params, Object object) {
        try {
            return questionInstanceService.create(object)
        } catch (Exception ex) {
            log.error(ex.message)
            return new Integer(0)
        }
    }

    public Object postCondition(Object params, Object object) {
        return null
    }
}